package com.example.demo.util;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.example.demo.entity.User;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * Jwt工具类
 */
public class JWTUtil {


    /**
     * 过期时间，一周
     */
    private static final long EXPIRE = 60000 * 60 * 24 * 7;


    /**
     * 加密秘钥
     */
    private static final String SECRET = "demoSecret";


    /**
     * 根据用户信息，生成令牌
     *
     * @param
     * @return
     */
    public static String getToken(User user) {
        return Jwts.builder().setSubject(user.getUsername())
                .claim("id", user.getId())
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + EXPIRE))
                .signWith(SignatureAlgorithm.HS256, SECRET).compact();
    }


    /**
     * 校验token
     *
     * @param token
     * @return
     */
    public static Claims checkToken(String token) {
        final Claims claims = Jwts.parser().setSigningKey(SECRET)
                .parseClaimsJws(token).getBody();
        return claims;
    }

    public static User getUser(HttpServletRequest request) {
        User user = null;
        String token = StringUtils.isBlank(request.getHeader("token")) ? request.getParameter("token") : request.getHeader("token");
        if (StringUtils.isNotBlank(token)) {
            final Claims claims = Jwts.parser().setSigningKey(SECRET)
                    .parseClaimsJws(token).getBody();
            user = User.builder().id(Long.valueOf(claims.get("id").toString())).
                    username(claims.getSubject()).
                    build();
        }
        return user;
    }
}
